package com.aid.winter.common.interceptor;

import cn.dev33.satoken.stp.StpUtil;
import com.aid.winter.common.annotation.RequiredRole;
import com.aid.winter.common.constant.RoleConstants;
import com.aid.winter.common.exception.BusinessException;
import com.aid.winter.common.enums.ResultCodeEnum;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;

@Aspect
@Component
public class RoleInterceptor {

    @Around("@annotation(com.aid.winter.common.annotation.RequiredRole)")
    public Object checkRole(ProceedingJoinPoint point) throws Throwable {
        // 获取注解
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        RequiredRole requiredRole = method.getAnnotation(RequiredRole.class);
        
        // 判断是否登录
        if (!StpUtil.isLogin()) {
            throw new BusinessException(ResultCodeEnum.UNAUTHORIZED);
        }
        
        // 获取当前用户角色
        Integer roleType = StpUtil.getSession().getInt("roleType");
        if (roleType == null) {
            throw new BusinessException(ResultCodeEnum.FORBIDDEN);
        }
        
        // 超级管理员直接放行
        if (roleType == RoleConstants.ROLE_ADMIN) {
            return point.proceed();
        }
        
        // 判断是否有所需角色
        boolean hasRole = Arrays.stream(requiredRole.value())
                .anyMatch(role -> role == roleType);
                
        if (hasRole) {
            return point.proceed();
        }
        
        throw new BusinessException(ResultCodeEnum.FORBIDDEN);
    }
} 